package com.example.micro.netty.server.nio.channel;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 本地文件写"hello world！" demo
 */
public class NIOFileChannelDemo1 {

    public static void main(String[] args) throws IOException {

        String str = "hello world!";

        //创建一个输出流 -> channel || 为什么是FileOutputStream？原生的输出流内置了通道
        FileOutputStream fileOutputStream = new FileOutputStream("/Users/didi/IdeaProjects/nio_file_demo1.txt");

        //通过FileOutputStream 获取 对应的FileChannel
        //这个FileChannel  真实类型是  FileChannelImpl
        FileChannel fileChannel = fileOutputStream.getChannel();

        //创建一个缓冲区ByteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        //将str 放入 byteBuffer
        byteBuffer.put(str.getBytes());

        //**对ByteBuffer 进行flip
        byteBuffer.flip();

        //将byteBuffer 数据写入到FileChannel
        fileChannel.write(byteBuffer);

        fileOutputStream.close();
    }

}
